import { defineStore } from 'pinia'
import { removeToken, getPayload, getToken, saveToken } from '@/utils'
import { ElMessage } from 'element-plus'

const useUserStore = defineStore('user', {
  state() {
    return {
      userId: '',
      username: '',
      role: '',
      tryLogin: false,
    }
  },
  actions: {
    reset() {
      this.userId = ''
      this.username = ''
      this.role = ''
    },
    async login(token) {
      if (token) {
        saveToken(token)
      }

      const _token = getToken()
      if (!_token) {
        throw new Error('未登录')
      }

      const payload = getPayload(_token)
      if (!payload) {
        removeToken()
        throw new Error('登录失败，请重新登录')
      }

      this.userId = payload.id ?? ''
      this.username = payload.username ?? ''
      this.role = payload.role ?? ''
    },
    logout() {
      removeToken()
      this.reset()
      ElMessage.success('退出登录成功')
    },
  },
  getters: {
    isLogined: state => !!state.userId,
    isAdmin: state => ['admin', 'superAdmin'].includes(state.role),
  },
})

export { useUserStore }
